XfMissionChapterExecute={
	private ["_chapter_succeeded"];
	diag_log "";
	diag_log "=========================================================================";
	diag_log "                             CHAPTER 1                                   ";
	diag_log "=========================================================================";
	diag_log "";
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Starting Chapter","_last_random_reinforcement","_random_reinf_diff","_reinforcement_power"];
	// This variable will hold all the groups of the reinforcement vehicles.
	DM_Mission_CounterAttackGroups = [];
	DM_Mission_Chapter_CanRun = True;
	DM_Mission_Chapter_Runs = True;
	DM_Mission_Chapter_Success = 0;
	
	call XfMissionChapterSetup;
	_chapter_succeeded = false;
	if (!DM_Mission_Mission_CanRun) exitWith {diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Mission canceled!"];};

	_random_town_pos = DM_Chapter_Location select 0;
	_random_town_size = DM_Chapter_Location select 3;
	_random_town_name = DM_Chapter_Location select 1;

	_players = call XPlayersNumber;
	_troops_counter_attack = 1;
	switch (true) do {
		case (_players <= 5): { _troops_counter_attack = 1 };
		case (_players <= 10): { _troops_counter_attack = 1 };
		case (_players <= 15): { _troops_counter_attack = 2 };
		case (_players <= 20): { _troops_counter_attack = 2 };
		default {_troops_counter_attack = 3;};
	};
	
	_conquer_updated = false;
	_counterattack_created = false;
	_counterattack_updated = false;
	_detected_update = false;
	_player_detected = false;
	// We use a greater area to take into account wandering troops or reinforcement nearly there.
	_start_enemy_counts = ([DM_Chapter_Position,500,d_enemy_side] call XfMissionGetZoneSideCount) select 0;
	_counter_attack_trigger = round(_start_enemy_counts * 0.15);
	_counter_attack_dead = false;
	diag_log Format["(%1)[%2]: %3: %4: %5, %6",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Lopatino Start",_start_enemy_counts,_counter_attack_trigger];
	sleep 10;
	while {DM_Mission_Chapter_CanRun AND DM_Mission_Mission_CanRun} do {
		sleep 15;
		_enemy_counts = ([_random_town_pos,_random_town_size,d_enemy_side] call XfMissionGetZoneSideCount) select 0;
		_lopatino_freed = ["jip_town_freed",false] call XNetGetJIP;
		if( ["jip_player_detected",false] call XNetGetJIP ) then { _player_detected = true; };
		_counter_attack_dead = !(["jip_town_counterattack",true] call XNetGetJIP);
		if (_lopatino_freed and !_conquer_updated) then {
			["FreeTown","", "","",[],"Succeeded"] call XfMissionTask;
			["STR_MF_M_SUNSET_CONQUERED",_random_town_name] call XfMissionMessageToAll;
			_conquer_updated = true;
		};
		If ((_counter_attack_dead and (_enemy_counts <= 3)) AND _counterattack_created AND !_counterattack_updated) then {
			["DefendTown","", "","",[],"Succeeded"] call XfMissionTask;
			_counterattack_updated = true;
			_chapter_succeeded = true;
			DM_Mission_Chapter_CanRun = false;
			"STR_MF_COUNTERATTACKDESTROYED" call XfMissionMessageToAll;
			["STR_MF_TOWNFREED",_random_town_name] call XfMissionMessageToAll;
		};

		// diag_log Format["(%1)[%2]: %3: %4, %5, %6",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute",_enemy_counts,_lopatino_freed,_counter_attack_alive];
		if ((_enemy_counts < _counter_attack_trigger) AND (!_counterattack_created) AND DM_Mission_Chapter_CanRun) then {
			If (!_conquer_updated) then {
				["FreeTown","", "","",[],"Succeeded"] call XfMissionTask;
				["STR_MF_M_SUNSET_CONQUERED",_random_town_name] call XfMissionMessageToAll;
				_conquer_updated = true;
			};
			["DefendTown",Format["Defend %1",_random_town_name], Format["STR_MF_M_SUNSET_DEFEND",_random_town_name],"",[],"Created"] call XfMissionTask;
			_counterattack_created = true;
			_counter_attack_dead= false;
			// We send footmen groups for reinforcement modulated by the counter attack power
			for [{_i = 0},{_i < (_troops_counter_attack * 2)},{_i = _i + 1}] do {
				["EAST",[_random_town_pos,_random_town_size],"MEN",1] call XfMissionCallReinforcement;
			};
			sleep 20;
			// Next we send vehicles. We will force the type of vehicle to avoid sending too heavy forces... but it is bad practice... avoid it :)
			if (_troops_counter_attack > 2) then {
				// Sending 1 tank if there are enough players
				["EAST",[_random_town_pos,_random_town_size],"VEH",1,0] call XfMissionCallReinforcement;
			};
			if (_troops_counter_attack > 1) then {
				// Heavy armored APC
				["EAST",[_random_town_pos,_random_town_size],"VEH",1,1] call XfMissionCallReinforcement;
			} else {	
				// One medium armored APC
				["EAST",[_random_town_pos,_random_town_size],"VEH",1,2] call XfMissionCallReinforcement;
			};
			if (_troops_counter_attack > 2) then {
				// One AA unit
				["EAST",[_random_town_pos,_random_town_size],"VEH",1,3] call XfMissionCallReinforcement;
			} else {	
				// One medium armored APC
				["EAST",[_random_town_pos,_random_town_size],"VEH",1,2] call XfMissionCallReinforcement;
			};
			if (_troops_counter_attack > 1) then {
				// Sending 1 heavy wheeled if there are enough players
				["EAST",[_random_town_pos,_random_town_size],"VEH",1,4] call XfMissionCallReinforcement;
			};
			// Heavy wheeled
			["EAST",[_random_town_pos,_random_town_size],"VEH",1,4] call XfMissionCallReinforcement;
			// UAZ linear with counter_attack size
			["EAST",[_random_town_pos,_random_town_size],"VEH",_troops_counter_attack,5] call XfMissionCallReinforcement;
			
			"STR_MF_COUNTERATTACKCOMING" call XfMissionMessageToAll;
			
			["jip_town_counterattack",true] call XNetSetJIP;
			["HeliHEmpty",_random_town_pos,"CONQUER",[Format["STR_MF_M_SUNSET_CLEAR",_random_town_name],[_random_town_pos, [(_random_town_size * 1.5),(_random_town_size * 1.5)], 0, false],d_enemy_side,"jip_town_counterattack",0]] call XfMissionCreateMissionObject;
			waituntil {
				sleep 10;
				((_enemy_counts < (([_random_town_pos,_random_town_size,d_enemy_side] call XfMissionGetZoneSideCount) select 0)) OR !DM_Mission_Chapter_CanRun OR !DM_Mission_Mission_CanRun)
			};
			// We wait an extra 5 minutes before we start polling variables again
			if (DM_Mission_Mission_CanRun && DM_Mission_Chapter_CanRun) then {sleep 300;};
		};
		if (DM_Mission_Chapter_CanRun && _counterattack_created) then {
			["jip_town_counterattack",true] call XNetSetJIP;
			if (count d_c_attacking_grps > 0) then {
				{
					if (alive (leader _x)) exitWith {["jip_town_counterattack",false] call XNetSetJIP;};
				} foreach d_c_attacking_grps;
			} else {
				["jip_town_counterattack",false] call XNetSetJIP;
			};
			// if (!_counterattack_updated && !_counter_attack_dead) then {
				// "The counter attackers are dead!" call XfMissionMessageToAll;
			// };
		};
		If (DM_Mission_Chapter_CanRun) then {
			if (_player_detected and !_detected_update) then {
				_detected_update = true;
				"STR_MF_PLAYERDETECTED" call XfMissionMessageToAll;
			};
			// diag_log Format["(%1)[%2]: %3: %4 %5",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Reinforcement:",[_player_detected,DM_Mission_RandomReinforcement,_enemy_counts,_start_enemy_counts,_counter_attack_trigger]];
			// Sending random reinforcement if configured in the mission editor and if there are enough remaining troops.
			If (_player_detected and (DM_Mission_RandomReinforcement > 0) and (_enemy_counts < (_start_enemy_counts - _counter_attack_trigger)) and (_enemy_counts  > _counter_attack_trigger)) then {
				if (([d_enemy_side,[_random_town_pos,_random_town_size],DM_Mission_RandomReinforcement] call XfMissionRandomReinforcement) > 0) then {
					// diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Random reinforcement sent!"];
				};
			};
		};
	};
	if (DM_Mission_Mission_CanRun) then {
		if (_chapter_succeeded) then {
			call XfMissionChapterSuccess;
		} else {
			call XfMissionChapterFailure;
		};
	} else {
		diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Mission canceled!"];
	};
	call XfMissionChapterCleanUp;
	DM_Mission_Chapter_Runs = False;
};

XfMissionChapterSetup={
	private ["_random_town","_random_town_pos","_random_town_size","_troops_power","_troops_coeff","_grpSpecOps1","_grpSpecOps2"];
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Starting Initialization"];

	// We filter only towns (the bigger ones)
	_random_town = call XfMissionGetRandomTown;
	_random_town_pos = _random_town select 0;
	while {(_random_town_pos distance FLAG_BASE) < 1000} do {
		_random_town = call XfMissionGetRandomTown;
		_random_town_pos = _random_town select 0;
	};
	if (isnil "_random_town") exitWith {"STR_MF_RANDOMTOWNFAILED" call XfMissionMessageToAll; DM_Mission_Mission_CanRun = false; DM_Mission_Chapter_CanRun = false;};
	if ((count _random_town) <= 0) exitWith {"STR_MF_RANDOMTOWNFAILED" call XfMissionMessageToAll; DM_Mission_Mission_CanRun = false; DM_Mission_Chapter_CanRun = false;};
	
	DM_Chapter_Position = _random_town_pos;
	DM_Chapter_Location = _random_town;
	_random_town_size = _random_town select 3;
	_random_town_name = _random_town select 1;
	diag_log Format["(%1)[%2]: %3: %4 %5",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Selected Town:",_random_town];

	// This indicates where the mission takes place
	[_random_town_pos,_random_town_size,_random_town_name] call XfMissionCurrentPosition;
	
	// We search a spot to place the teleporter which is around the town on a road (to avoid mountains and forests)
	_teleporter = [_random_town_pos] call XfMissionRandomStartTeleporter;
	// If no spot found, we get back an empty position.
	if (count (_teleporter select 0) > 0) then {
		[false,["chapter1_start_position",(_teleporter select 0), "ICON", "ColorBlue", [1,1],"",(_teleporter select 1),"hd_start","",1]] call XfMissionMarker;
	};

	// The marker which indicates the war zone	
	[false,["chapter1_town_position", _random_town_pos, "ELLIPSE", "ColorRed", [(_random_town_size * 1.5),(_random_town_size * 1.5)],"",0,"","BDiagonal",0.5]] call XfMissionMarker;
	[false,["chapter1_town_cross",_random_town_pos, "ICON", "ColorRed", [1,1],"",20,"hd_destroy","",0.6]] call XfMissionMarker;

	[d_enemy_side,[_random_town_pos,_random_town_size],true] call XfMissionPopulateLocation;
	// We create two groups which will wait and ambush in town.
	_random_point = [_random_town_pos, (_random_town_size / 2)] call XfGetRanPointCircle;
	_grpSpecOps1 = [d_enemy_side,[_random_point,50],[],1,false] call XfMissionCreateFootmenGroup;
	_random_point = [_random_town_pos, (_random_town_size / 2)] call XfGetRanPointCircle;
	_grpSpecOps2 = [d_enemy_side,[_random_point,50],[],1,false] call XfMissionCreateFootmenGroup;
	
	// We now create the "object" which is used to create the zone to conquer. It serves as a variable holder more than anything.
	["jip_town_freed",false] call XNetSetJIP;
	["jip_town_counterattack",false] call XNetSetJIP;
	["HeliHEmpty",_random_town_pos,"CONQUER",["",[_random_town_pos, [(_random_town_size * 1.5),(_random_town_size * 1.5)], 0, false],d_enemy_side,"jip_town_freed"]] call XfMissionCreateMissionObject;
	["FreeTown",["STR_MF_FREEZONE",_random_town_name], ["STR_MF_M_SUNSET_DRIVEOUT",_random_town_name],"",[],"Created"] call XfMissionTask;

	_players = call XPlayersNumber;
	_troops_counter_attack = 1;
	switch (true) do {
		case (_players <= 5): { _troops_counter_attack = 1 };
		case (_players <= 10): { _troops_counter_attack = 1 };
		case (_players <= 15): { _troops_counter_attack = 2 };
		case (_players <= 20): { _troops_counter_attack = 2 };
		default {_troops_counter_attack = 3;};
	};
	
	// The trigger which will send reinforcement when the player is detected!
	["jip_player_detected",false] call XNetSetJIP;
	[_random_town_pos,_random_town_size,d_own_side,d_enemy_side,"jip_player_detected"] call XfMissionSideDetected;
	
	// This will create snipers automatically if selected in the mission setup
	[d_enemy_side,[_random_town_pos,_random_town_size],DM_Mission_Snipers] call XfMissionCreateSnipersArea;
	// This will create air support automatically if selected in the mission setup
	[d_enemy_side,[_random_town_pos,_random_town_size],DM_Mission_AirSupport] call XfMissionCallAirSupport;
};

XfMissionChapterSuccess={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSuccess","Starting"];
	DM_Mission_Chapter_Success = 1;
};

XfMissionChapterFailure={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterFailure","Starting"];
	"STR_MF_MISSIONFAILURE1" call XfMissionMessageToAll;
	DM_Mission_Chapter_Success = -1;
};

// Self-explanatory
XfMissionChapterCleanUp={
	[false,["chapter1_start_misson"]] call XfMissionMarker;
	[false,["chapter1_town_position"]] call XfMissionMarker;
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterCleanUp","Starting"];
	// Giving an empty position places the teleporter back to the hangar, closing the hangar.
	[[],0] call XfMissionPlaceStartTeleporter;
	[] call XfMissionCleanObjects;
	[] call XfMissionCleanMarkers;
	[] call XfMissionCleanTriggers;
	[] call XfMissionCleanTasks;
};

DM_Mission_Chapter_Compiled = true;